﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./AgentList.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 20;
    public string strPager = "";
    public string strError = "";
    public string strMess = "";
    public string strProcessName = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["sesSeachCountry"] == null)
            Session["sesSeachCountry"] = "";
        if (Session["sesSeachCity"] == null)
            Session["sesSeachCity"] = "";
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;

        if ((Session["agentlist"] != null) && (int.Parse(Session["agentlist"].ToString()) > 0))
        {
            if (Session["agentlist"] != "") nPermissions = int.Parse(Session["agentlist"].ToString());
        }
        else
            Response.Redirect("Login.aspx");

        if (!Page.IsPostBack)
        {

            loadDropdownCountry();
            if (Session["sesSeachCountry"].ToString() != "")
                loadDropdownCity(Session["sesSeachCountry"].ToString());
            if (Session["sesSeachDisplay"] != null && Session["sesSeachDisplay"].ToString() != "")
                ddDisplay.SelectedValue = Session["sesSeachDisplay"].ToString();
            if (nPermissions < 3) ddDisplay.Visible = false;
            if (Request.QueryString["action"] == "delete" && nPermissions > 7)
            {
                AgentList obj = new AgentList();
                obj.ID = long.Parse(Request.QueryString["AgentID"]);
                obj.Load(GV.cn, GV.trans);
                obj.Delete(GV.cn, GV.trans);
                Response.Redirect("AgentList.aspx" + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "?page_number=" + Request.QueryString["page_number"].ToString() : ""));
            }
            else
            {
                if (Request.QueryString["AgentID"] != null)
                {
                    loadAgent();
                }
            }
            if (nPermissions >= 1)
            {
                #region Build List
                int nNumOfPages = 0;

                DataTable dtList;
                BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
                if (nPage > nNumOfPages) nPage = 1;

                rptData.DataSource = dtList;
                rptData.DataBind();
                #endregion
                #region Build Pager
                CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
                #endregion
            }
        }

    }
    protected void loadAgent()
    {
        AgentList obj = new AgentList();
        obj.ID = long.Parse(Request.QueryString["AgentID"]);
        obj.Load(GV.cn, GV.trans);
        txtCountry.Text = obj.Country;
        txtCity.Text = obj.City;
        txtAgent.Text = obj.Agent;
        txtAddress.Text = obj.Address;
        txtDescription.Text = obj.Description;
        cbDisplay.Checked = obj.Display == 1 ? true : false;
        obj.LastUpdate = DateTime.Now;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        AgentList obj = new AgentList();
        obj.ID = -1;
        if (Request.QueryString["AgentID"] != null)
        {
            obj.ID = long.Parse(Request.QueryString["AgentID"]);
            obj.Load(GV.cn, GV.trans);
        }
        else
        {
            if (txtAgent.Text == "")
            {
                strError = "NotBlank";
                strMess = "Agent Name not blank!";
            }
        }
        if (nPermissions >= 7)
        {
            obj.Country = txtCountry.Text.Trim();
            obj.City = txtCity.Text.Trim();
            obj.Agent = txtAgent.Text.Trim();
            //Check Validate Coutry and City
            string sql = "Select ID From tbl_ports where Name like '%" + DBModule.RefineString(txtCity.Text.Trim()) + "%' and trim(Country) ='" + DBModule.RefineString(txtCountry.Text.Trim()) + "'";
            DataSet ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
            if (ds.Tables[0].Rows.Count <= 0)
                strMess += "<br>Tên quốc gia hoặc tên thành phố không hợp lệ!";
        }
        obj.Address = txtAddress.Text.Trim();
        obj.Description = txtDescription.Text.Trim();
        obj.LastUpdate = DateTime.Now;
        obj.Display = cbDisplay.Checked == true ? 1 : 0;
        if (strMess == "")
        {
            obj.Save(GV.cn, GV.trans);
            Response.Redirect("AgentList.aspx" + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "?page_number=" + Request.QueryString["page_number"].ToString() : ""));
        }
        else
            ErrMessage.Text = strMess;
    }

    private void BuildList(string strCondition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Sort");
        dtList.Columns.Add("Index");
        dtList.Columns.Add("Country");
        dtList.Columns.Add("City");
        dtList.Columns.Add("Agent");
        dtList.Columns.Add("Address");
        dtList.Columns.Add("Mobile");
        dtList.Columns.Add("Description");
        dtList.Columns.Add("LastUpdate");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;
        //string strCondition = "";
        AgentList obj = new AgentList();
        if (Session["sesSeachCountry"].ToString() != "")
            strCondition = " AND country='" + DBModule.RefineString(Session["sesSeachCountry"].ToString()) + "'";

        if (Session["sesSeachCity"].ToString() != "")
            strCondition += " AND City='" + DBModule.RefineString(Session["sesSeachCity"].ToString()) + "'";
        //Visibled if Pemission is View when Display=0
        if (nPermissions <= 1)
            strCondition += " And Display=1";
        if (Session["sesSeachDisplay"] != null && Session["sesSeachDisplay"].ToString() != "")
            strCondition += " And Display=" + Session["sesSeachDisplay"].ToString();
        obj.GetList(strCondition, "Country", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";

        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);

        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {


                count++;
                string strSTT = dr["Sort"].ToString();
                string strIndex = count.ToString();
                string strCountry = dr["Country"].ToString();
                string strCity = dr["City"].ToString();
                string strAgent = dr["Agent"].ToString();
                string strAddress = HttpUtility.HtmlEncode(dr["Address"].ToString());
                string strMobile = dr["Mobile"].ToString();
                string strDescription = dr["Description"].ToString();
                string strLastUpdate = dr["LastUpdate"].ToString();
                if (dr["LastUpdate"].ToString() != "")
                {
                    strLastUpdate = DateTime.Parse(dr["LastUpdate"].ToString()).ToString("ddMMyy");
                }
                string strAction = "";
                if (nPermissions >= 3)
                {
                    strAction = "<a href=\"AgentList.aspx?&AgentID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") + "\">Edit</a>";
                    strAction += " - <a href=\"javascript:openAgentDetail('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strAgent.Replace("'", "")) + "')\">" + "View</a>";
                }
                if (nPermissions > 7)
                    strAction += " - <a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strAgent.Replace("'", "")) + "')\">" + "Delete</a>";

                string[] strValues = new string[] { strSTT, strIndex, strCountry, strCity, strAgent, strAddress, strMobile, strDescription, strLastUpdate, strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string strCondition = "";
        Session["sesSeachCountry"] = drCountrySearch.SelectedValue.ToString();
        Session["sesSeachCity"] = drCitySearch.SelectedValue.ToString();
        Session["sesSeachDisplay"] = ddDisplay.SelectedValue.ToString();
        if (drCountrySearch.SelectedValue.ToString() != "")
        {
            strCondition = " AND country='" + DBModule.RefineString(drCountrySearch.SelectedValue.ToString()) + "'";
        }
        if (drCitySearch.SelectedValue.ToString() != "")
        {
            strCondition += " AND City='" + DBModule.RefineString(drCitySearch.SelectedValue.ToString()) + "'";
        }
        if (ddDisplay.SelectedValue.ToString() != "")
        {
            strCondition += " AND Display='" + DBModule.RefineString(ddDisplay.SelectedValue.ToString()) + "'";
        }
        if (txtAgentSearch.Text.Trim() != "")
            strCondition += " AND Agent like '%" + DBModule.RefineString(txtAgentSearch.Text.ToString().Trim()) + "%'";
        #region Build List
        int nNumOfPages = 0;
        DataTable dtList;
        BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
        if (nPage > nNumOfPages) nPage = 1;

        rptData.DataSource = dtList;
        rptData.DataBind();
        #endregion
        #region Build Pager
        CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
        #endregion

    }
    protected void loadDropdownCountry()
    {
        string sql = "";
        DataSet ds = null;
        sql = "SELECT DISTINCT country FROM tbl_agentlist ORDER BY Country";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
        DataTable dtb = ds.Tables[0];
        drCountrySearch.DataSource = dtb;
        drCountrySearch.DataTextField = dtb.Columns[0].ToString();
        drCountrySearch.DataBind();
        drCountrySearch.Items.Insert(0, "");
        //drCountrySearch.Items.Insert(0, new ListItem("Select Country", ""));

        if (Session["sesSeachCountry"] != null)
        {
            drCountrySearch.SelectedValue = Session["sesSeachCountry"].ToString();
            //loadDropdownCity(Session["sesSeachCountry"].ToString());
        }
    }
    protected void loadDropdownCity(string country)
    {
        string sql = "";
        DataSet ds = null;
        sql = "SELECT DISTINCT city FROM tbl_agentlist where Country='" + DBModule.RefineString(country) + "'  ORDER BY city ";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
        DataTable dtb = ds.Tables[0];
        drCitySearch.DataSource = dtb;
        drCitySearch.DataTextField = dtb.Columns[0].ToString();
        drCitySearch.DataBind();
        drCitySearch.Items.Insert(0, "");
        //ListItem litems = new ListItem("Select City", "");
        //drCitySearch.Items.Insert(0, litems);       
        if (Session["sesSeachCity"] != null)
        {
            if (drCitySearch.Items.FindByValue(Session["sesSeachCity"].ToString()) != null)
                drCitySearch.SelectedValue = Session["sesSeachCity"].ToString();
        }
    }
    protected void txtCountrySearch_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadDropdownCity(drCountrySearch.SelectedValue.ToString());
        Session["sesSeachCountry"] = drCountrySearch.SelectedValue.ToString();
        Session["sesSeachCity"] = "";
        Response.Redirect("AgentList.aspx");
    }
}
